package test.closure

def closure = { param -> println("hello${param}") }
closure.call("world!")
closure = { greeting, name -> println(greeting + name) }
closure.call("hello ", "world!")


def closure2 = { println "hello " + it }
closure2.call("world!")


[1, 2, 3].each({ item -> print "${item}-" })
["k1": "v1", "k2": "v2"].each { key, value -> println key + "=" + value }


def fun(int i, Closure c) {
    c.call(i)
}
// put Closure out of ()
[1, 2, 3].each() { item -> print "${item}-" } // 1-2-3-fun(123) { i -> println i } // 123
// omit ()
[1, 2, 3].each({ item -> print "${item}-" }) // 1-2-3-// omit enclosing ()
[1, 2, 3].each { item -> print "${item}-" }
// 1-2-3-// normal
[1, 2, 3].each(({ item -> print "${item}-" })) // 1-2-3-// using the fun function to do the same thing
[1, 2, 3].each { fun(it, { item -> print "${item}-" }) } // 1-2-3-def closure = { i -> println i}
//[1, 2, 3].each() closure // error. closurehas been previously defined


def value = [1, 2, 3].collect { it * 2 }
assert value == [2, 4, 6]

def value2 = [1, 2, 3].find { it > 1 }
assert value2 == 2
// filters: findAll, grep
def value3 = [1, 2, 3].findAll { it > 1 }
assert value3 == [2, 3]
assert [2, 3] == [1, 2, 3].grep({ it > 1 })


def value4 = [1, 2, 3].inject('counting: ') { str, item -> str + item }
assert value4 == "counting: 123"
value5 = [1, 2, 3].inject(0) { count, item -> count + item }
assert value5 == 6


def value6 = [1, 2, 3].every { it < 5 }
assert value6
value7 = [1, 2, 3].every { item -> item < 3 }
assert !value7


def value8 = [1, 2, 3].any { it > 2 }
assert value8
value9 = [1, 2, 3].any { item -> item > 3 }
assert value9 == false


value10 = [9, 4, 2, 10, 5].max()
assert value10 == 10
value11 = [9, 4, 2, 10, 5].min()
assert value11 == 2
value12 = ['x', 'y', 'a', 'z'].min()
assert value12 == 'a'

def value13 = [1, 2, 3].join('-')
assert value13 == '1-2-3'
